package org.tczs93.springsecurity.config.security;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Configurable;
import org.springframework.context.annotation.Bean;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

/**
 * @author ：tao.li
 * @description：security配置中心
 * @date ：Created in 2021/8/27 17:54
 */
@Configurable
@EnableWebSecurity
public class CustomerWebSecurity extends WebSecurityConfigurerAdapter {

    @Autowired
    private TokenAuthenticationFilter tokenAuthenticationFilter;

    @Bean
    public AccessDeniedHandler getAccessDeniedHandler() {
        return new CustomerAuthorizationAccessDeniedHandler();
    }

    @Bean
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    @Bean
    public CustomerAuthenticationEntryPoint getCustomerAuthenticationEntryPoint() {
        return new CustomerAuthenticationEntryPoint();
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests() //认证请求
                .antMatchers(PermitAllInterface.INTERFACE_ARRAY).permitAll()  //放行的接口
                .antMatchers("/user/**").access("hasRole('USER')") //配置角色权限
                .antMatchers("/admin/**").access("hasRole('ADMIN')")
                .anyRequest().authenticated() //除放行接口,所有的接口都需要认证
                .and()
                .exceptionHandling().authenticationEntryPoint(getCustomerAuthenticationEntryPoint()) //401错误处理器
                .accessDeniedHandler(getAccessDeniedHandler()) //403错误处理器
                .and()
                .addFilterBefore(tokenAuthenticationFilter, UsernamePasswordAuthenticationFilter.class) //token认证过滤器
                .csrf().disable();
    }

}
